<?php

namespace RjYst\Category\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use RjYst\Category\Services\DatabaseConfigUpdater;
use Database\Seeders\AdminMenuSeeder;

class UninstallCategoryCommand extends Command
{
    protected $signature = 'rjyst:uninstall-category {--keep-files : 保留已发布的文件}';
    protected $description = 'Uninstall RjYst Category Package';

    public function handle()
    {
        $this->info('🗑️ 开始卸载 RjYst Category Package...');

        if (!$this->confirm('确定要卸载 RjYst Category Package 吗？')) {
            $this->info('❌ 卸载已取消');
            return;
        }

        // 1. 移除后台菜单
        $this->removeAdminMenus();

        // 2. 移除数据库配置
        $this->removeDatabaseConfig();

        // 3. 移除发布的文件（可选）
        if (!$this->option('keep-files')) {
            $this->removePublishedFiles();
        }

        // 4. 移除路由配置
        $this->removeRoutes();

        $this->info('✅ RjYst Category Package 卸载完成！');
    }

    protected function removeAdminMenus()
    {
        $this->info('🎛️ 移除后台菜单...');

        try {
            AdminMenuSeeder::removeMenus();
            $this->info('✅ 后台菜单移除完成');
        } catch (\Exception $e) {
            $this->error('❌ 移除后台菜单时出错: ' . $e->getMessage());
        }
    }

    protected function removeDatabaseConfig()
    {
        $this->info('🗄️ 移除数据库配置...');

        try {
            if (DatabaseConfigUpdater::hasRjmysqlConfig()) {
                DatabaseConfigUpdater::removeRjmysqlConfig();
                $this->info('✅ rjmysql 数据库配置已移除');
            } else {
                $this->info('ℹ️ rjmysql 配置不存在，跳过移除');
            }
        } catch (\Exception $e) {
            $this->error('❌ 移除数据库配置时出错: ' . $e->getMessage());
        }
    }

    protected function removePublishedFiles()
    {
        $this->info('📦 移除已发布的文件...');

        $files = [
            app_path('Models/Category/Category.php'),
            app_path('Admin/Controllers/Category/CategoryController.php'),
            app_path('Admin/Repositories/Category/Category.php'),
            config_path('rjyst-category.php'),
            database_path('seeders/CategorySeeder.php'),
            database_path('seeders/AdminMenuSeeder.php'),
        ];

        foreach ($files as $file) {
            if (File::exists($file)) {
                File::delete($file);
                $this->line("   - 删除: {$file}");
            }
        }

        // 删除空目录
        $directories = [
            app_path('Models/Category'),
            app_path('Admin/Controllers/Category'),
            app_path('Admin/Repositories/Category'),
        ];

        foreach ($directories as $dir) {
            if (File::exists($dir) && File::isDirectory($dir) && count(File::files($dir)) === 0) {
                File::deleteDirectory($dir);
                $this->line("   - 删除空目录: {$dir}");
            }
        }

        $this->info('✅ 已发布的文件移除完成');
    }

    protected function removeRoutes()
    {
        $this->info('🔗 移除路由配置...');

        $routesFile = app_path('Admin/routes.php');

        if (!File::exists($routesFile)) {
            $this->info('ℹ️ 路由文件不存在，跳过移除');
            return;
        }

        $routes = File::get($routesFile);

        // 移除分类路由
        $routes = preg_replace("/\s*\\\$router->resource\('category',\s*'Category\\\\CategoryController'\);\s*/", '', $routes);

        File::put($routesFile, $routes);
        $this->info('✅ 路由配置移除完成');
    }
}
